'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	const uniIdToken = event.uniIdToken
	if (!uniIdToken) {
		return {
			code: 1002,
			desc: '您还没有登录，禁止访问'
		}
	}
	const params = event.params
	let uid = params.uid || ''
	if (!uid) {
		return {
			code: 2,
			desc: '没有检测到 uid 参数'
		}
	}
	let userinfo = await db.collection('uni-id-users').doc(uid).get();
	if (userinfo.data.length === 0) {
		return {
			code: 2,
			desc: '未查询到用户信息'
		}
	}
	if (!params.name || !params.path) {
		return {
			code: 2,
			desc: '参数错误'
		}
	}
	let project = await db.collection('db-project-list').where(db.command.or({
		project_name: params.name
	}, {
		project_base_path: params.path
	})).get()
	// 验重
	if (project.data.length > 0) {
		let pdata = project.data
		let msg = ''
		for (let i = 0; i < pdata.length; i++) {
			// 只验证同一个用户
			if (pdata[i].user_id === uid) {
				if (params.name === pdata[i].project_name) {
					msg = '项目名称已经存在'
					break
				}
				if (params.path === pdata[i].project_base_path) {
					msg = '基础路径已经存在'
					break
				}
			}
		}

		return {
			code: 2,
			desc: msg
		}
	}

	let addObj = {
		"user_id": uid,
		"project_name": params.name,
		"project_base_path": params.path,
		"comment": params.comment || '',
		"created_date": Date.now(),
		"status": 1,
		"apis": []
	}
	// 添加数据
	let projectCallback = await db.collection('db-project-list').add({
		"user_id": uid,
		"project_name": params.name,
		"project_base_path": params.path,
		"comment": params.comment || '',
		"created_date": Date.now(),
		"status": 1,
		"apis": []
	});

	if (!projectCallback.id) {
		return {
			code: 2,
			desc: '新建项目失败'
		}
	}
	addObj._id = projectCallback.id
	//event为客户端上传的参数
	console.log(projectCallback);
	//返回数据给客户端
	return {
		code: 0,
		desc: '项目创建成功',
		data:addObj
	}
};
